<script setup>
import { nextTick, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { Message } from "@arco-design/web-vue";
import schoolApi from "@/api/schoolApi";
import userApi from "@/api/userApi";
import studentApi from "@/api/studentApi";
import constants from "@/utils/constants";
import UploadAvatar from "@/components/UploadAvatar.vue";
import Upload from "@/components/Upload.vue";

const router = useRouter();

const submitForm = ref();
const searchForm = ref();
const changeClassForm = ref();
const searchModel = reactive({
  schoolId: "",
  gradeId: "",
  graduateFlag: false
});
const changeClassData = ref({
  studentIds: [],
  classesId: "",
});
const visible = ref(false);
let uploadVisible = ref(false);
let avatarUploadVisible = ref(false);
let changeClassesVisible = ref(false);
const isChangeClasses = ref(false);
const changeDialogTitle = ref("");
const loading = ref(false);
const isCollege = ref(false);
const showUpdateGradeDialog = ref(false);
const updateGradeModel = reactive({
  schoolId: "",
  excludeStudyCodeStr: "",
  includeStudyCodeStr: ""
})

let submitData = ref({
  schoolId: "",
  sex: "1",
  avatarUrl: ""
});
let uploadData = ref({
  schoolId: "",
  studyCode: ''
});
let schoolList = reactive([]);
let gradeClassesList = reactive([]);
let classesList = reactive([]);
let submitClassesList = ref([]);
let changeClassesList = reactive([]);
let pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 15,
  showPageSize: true,
  pageSizeOptions: [15, 25, 30, 50],
  showTotal: true,
  pageChange: (current) => {
    pagination.current = current;
    search();
  },
  pageSizeChange(size) {
    pagination.pageSize = size;
    search();
  },
});

const columns = [
  {
    title: "头像",
    slotName: "avatar",
    width: 100,
  },
  {
    title: "学生姓名",
    dataIndex: "name",
    width: 100,
  },
  {
    title: "性别",
    slotName: "sex",
    width: 100,
  },
  {
    title: "出生日期",
    dataIndex: "birthday",
    width: 120,
  },
  {
    title: "民族",
    slotName: "nation",
    width: 100,
  },
  {
    title: "学校名称",
    dataIndex: "schoolName",
    width: 150,
  },
  {
    title: "学院名称",
    dataIndex: "collegeName",
    width: 120,
  },
  {
    title: "年级",
    dataIndex: "gradeName",
    width: 100,
  },
  {
    title: "所属班级",
    dataIndex: "classesName",
    width: 100,
  },
  {
    title: "学籍号",
    dataIndex: "studyCode",
    width: 200,
  },
  {
    title: "身份证号",
    dataIndex: "idNumber",
    width: 200,
  },
  {
    title: "IC卡号",
    dataIndex: "cardNo",
    width: 150,
  },
  {
    title: "学生来源",
    dataIndex: "fromSource",
    width: 100,
  },
  {
    title: "家庭地址",
    dataIndex: "address",
    width: 200,
  },
  {
    title: "录入时间",
    dataIndex: "createTime",
    width: 180,
  },
  {
    title: "操作",
    slotName: "action",
    fixed: "right",
    width: 200,
  },
];

const uploadErrorList = ref([]);
const data = ref([]);

const selectedStudentIds = ref([]);
const rowSelection = reactive({
  type: "checkbox",
  showCheckedAll: true,
  onlyCurrent: false,
});

const showAddDialog = () => {
  visible.value = true;
  submitForm.value.resetFields();
  submitData.value = {
    schoolId: "",
    sex: "1",
    avatarUrl: ""
  };
};

const querySchoolList = () => {
  userApi
    .queryManagerSchoolList()
    .then((res) => {
      schoolList = res;
      if (res.length == 1) {
        searchModel.schoolId = res[0].id;
        schoolChange(searchModel.schoolId);
        search();
      }
    });
};

const showUpdateGrade = () => {
  showUpdateGradeDialog.value = true;
}

const schoolChange = (schoolId) => {
  if (schoolId) {
    submitData.value.schoolId = schoolId;
    uploadData.value.schoolId = schoolId;
    queryGradeListBySchoolId();
    getGradeClassesList();
  } else {
    gradeClassesList = [];
    classesList = [];
    submitData.value.schoolId = "";
    uploadData.value.schoolId = "";
  }
}

const schoolSubmitChange = (schoolId) => {
  if (schoolId) {
    submitData.value.schoolId = schoolId;
    uploadData.value.schoolId = schoolId;
    queryGradeListBySchoolId(schoolId);
    getGradeClassesList(schoolId);
  } else {
    submitGradeClassesList.value = [];
    submitClassesList.value = [];
    submitData.value.schoolId = "";
    uploadData.value.schoolId = "";
  }
}

const queryGradeListBySchoolId = (schoolId) => {
  schoolApi.getGradeList({
    schoolId: schoolId ? schoolId : searchModel.schoolId
  }).then(res => {
    let collegeGrades = res.find(item => parseInt(item) > 41);
    if (collegeGrades && collegeGrades.length > 0) {
      isCollege.value = true;
    }
  })
}

const showChangeClassesDialog = () => {
  changeClassesVisible.value = true;
  changeDialogTitle.value = "批量转班";
  // isChangeClasses.value = true;
};

const showKeepGradeDialog = (record) => {
  changeClassesVisible.value = true;
  isChangeClasses.value = false;
  selectedStudentIds.value = [record.id];
  changeDialogTitle.value = "留级";
};

const showUploadDialog = () => {
  uploadVisible.value = true;
  uploadErrorList.value = [];
};

const showAvatarUploadDialog = () => {
  avatarUploadVisible.value = true;
};

const editRecord = (record) => {
  visible.value = true;
  getGradeClassesListBySchoolId(record.schoolId);
  nextTick(() => {
    submitForm.value.resetFields();
    changeSubmitGrade(record.gradeId);
    submitData.value = Object.assign({}, record);
    uploadData.value.studyCode = record.studyCode;
  });
};

const deleteRecord = (record) => {
  studentApi
    .delete({
      id: record.id,
    })
    .then((res) => {
      search();
    });
};

const deleteStudents = () => {
  studentApi
    .batchDelete({
      ids: selectedStudentIds.value
    })
    .then((res) => {
      search();
    });
}

const handleSubmitSuccess = (values, e) => {
  studentApi.save(values).then((res) => {
    visible.value = false;
    Message.success("保存成功");
    search();
  });
};

const updateGradeSuccess = (values) => {
  Message.conf
}

const sureChangeClasses = (values) => {
  values.studentIds = selectedStudentIds.value;
  studentApi.changeClasses(values).then((res) => {
    changeClassesVisible.value = false;
    selectedStudentIds.value = [];
    Message.success("转班操作成功");
    refresh();
  });
};

const changeSelectGrade = (gradeId) => {
  let gradeModel = gradeClassesList.find((grade) => {
    return grade.id == gradeId;
  });
  if (
    gradeModel &&
    gradeModel.classesList &&
    gradeModel.classesList.length > 0
  ) {
    classesList = gradeModel.classesList;
  } else {
    searchModel.classesId = "";
    classesList = [];
  }
};

const changeSubmitGrade = (gradeId) => {
  let gradeModel = submitGradeClassesList.value.find((grade) => {
    return grade.id == gradeId;
  });
  if (
    gradeModel &&
    gradeModel.classesList &&
    gradeModel.classesList.length > 0
  ) {
    submitClassesList.value = gradeModel.classesList;
    submitData.value.classesId = gradeModel.classesList[0].id
  } else {
    submitData.value.classesId = "";
    submitClassesList.value = [];
  }
};

const changeClassesSubmitGrade = (gradeId) => {
  let gradeModel = gradeClassesList.find((grade) => {
    return grade.id == gradeId;
  });
  if (
    gradeModel &&
    gradeModel.classesList &&
    gradeModel.classesList.length > 0
  ) {
    changeClassesList = gradeModel.classesList;
  } else {
    changeClassData.classesId = "";
    changeClassesList = [];
  }
};

const submitGradeClassesList = ref([]);
const getGradeClassesListBySchoolId = (schoolId) => {
  schoolApi
    .getGradeClassesList({
      schoolId: schoolId,
    })
    .then((res) => {
      submitGradeClassesList.value = res;
    });
};

const getGradeClassesList = (schoolId) => {
  schoolApi
    .getGradeClassesList({
      schoolId: schoolId ? schoolId : searchModel.schoolId,
    })
    .then((res) => {
      if (schoolId) {
        submitGradeClassesList.value = res;
      } else {
        gradeClassesList = res;
      }
    });
};

const search = () => {
  var params = {
    pageNo: pagination.current,
    pageSize: pagination.pageSize,
    queryParam: Object.assign({}, searchModel),
  };
  loading.value = true;
  studentApi.page(params).then((res) => {
    data.value = res.records;
    pagination.total = res.total;
    loading.value = false;
  });
};

const refresh = () => {
  search();
};

const getNationName = (value) => {
  let nationItem = constants.nationList.find((res) => {
    return res.value == value;
  });
  return !nationItem ? "" : nationItem.label;
};

const reset = () => {
  searchForm.value.resetFields();
  gradeClassesList = [];
  classesList = [];
  searchModel.classesId = "";
  searchModel.gradeId = "";
};

const closeUploadDialog = () => {
  uploadVisible.value = false;
  avatarUploadVisible.value = false;
  refresh();
};

const admissionTicketDialog = ref(false);
const showAdmissionTicketDialog = () => {
  router.push({ name: 'AdmissionTicket' });
}

querySchoolList();

</script>

<template>
  <div class="main-con">
    <a-card>
      <a-row>
        <a-col :flex="1">
          <a-form ref="searchForm" :model="searchModel" :label-col-props="{ span: 8 }" :wrapper-col-props="{ span: 16 }"
            label-align="left">
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="schoolId" label="选择学校">
                  <a-select v-model="searchModel.schoolId" placeholder="请选择" allow-search allow-clear
                    @change="schoolChange">
                    <a-option v-for="s in schoolList" :key="s.id" :label="s.name" :value="s.id"></a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="gradeId" label="年级/班级">
                  <a-space>
                    <a-select v-model="searchModel.gradeId" @change="changeSelectGrade" placeholder="年级">
                      <a-option value="">全部</a-option>
                      <a-option v-for="item in gradeClassesList" :key="item.id" :value="item.id">{{ item.name
                      }}</a-option>
                    </a-select>
                    <a-select style="width: 150px;" v-model="searchModel.classesId" placeholder="班级">
                      <a-option value="">全部</a-option>
                      <a-option v-for="classes in classesList" :key="classes.id" :value="classes.id">{{ classes.name
                      }}</a-option>
                    </a-select>
                  </a-space>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="name" label="学生姓名">
                  <a-input v-model="searchModel.name" placeholder="请输入姓名" />
                </a-form-item>
              </a-col>

            </a-row>
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="sex" label="性别">
                  <a-select v-model="searchModel.sex" placeholder="请选择性别">
                    <a-option value="1">男</a-option>
                    <a-option value="2">女</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="studyCode" label="学籍号">
                  <a-input v-model="searchModel.studyCode" placeholder="请输入学籍号" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="idNumber" label="身份证号">
                  <a-input v-model="searchModel.idNumber" placeholder="请输入身份证号" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="cardNo" label="IC卡号">
                  <a-input v-model="searchModel.cardNo" placeholder="请输入IC卡号" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search(1, 15)">
              <template #icon>
                <icon-search />
              </template>
              查询
            </a-button>
            <a-button @click="reset">

              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-card>
    <a-card style="margin-top: 20px">
      <div class="toolbar">
        <a-space>
          <a-button type="primary" @click="showAddDialog">

            <template #icon>
              <icon-plus />
            </template>
            新增学生
          </a-button>
          <a-tooltip content="先选择上方学校后才可操作">
            <a-button type="outline" @click="showUploadDialog">
              <template #icon>
                <icon-upload />
              </template>
              导入学生
            </a-button>
          </a-tooltip>
          <a-tooltip content="先选择上方学校后才可操作">
            <a-button type="outline" @click="showAvatarUploadDialog">
              <template #icon>
                <icon-image />
              </template>
              导入学生头像
            </a-button>
          </a-tooltip>
          <a-tooltip content="先选择学生数据才可操作">
            <a-button :disabled="selectedStudentIds.length == 0" type="outline" @click="showChangeClassesDialog">

              <template #icon>
                <icon-user-add />
              </template>
              批量转班
            </a-button>
          </a-tooltip>
          <a-popconfirm content="确认要删除选中学生数据吗？" @ok="deleteStudents">
            <a-button :disabled="selectedStudentIds.length == 0" type="outline">
              <template #icon>
                <icon-delete />
              </template>
              批量删除
            </a-button>
          </a-popconfirm>
          <!-- <a-button type="outline" @click="showAdmissionTicketDialog">
            <template #icon>
              <icon-edit />
            </template>
            准考证设计
          </a-button> -->
          <!-- <a-button type="outline" @click="showUpdateGrade">
          <template #icon>
            <icon-arrow-rise />
          </template>
          一键升班
        </a-button> -->
        </a-space>
      </div>
      <a-table :row-selection="rowSelection" v-model:selectedKeys="selectedStudentIds" :columns="columns" row-key="id"
        :loading="loading" :data="data" @page-change="pagination.pageChange"
        @page-size-change="pagination.pageSizeChange" :pagination="pagination" :bordered="false">

        <template #nation="{ record }">
          {{ getNationName(record.nation) }}
        </template>

        <template #avatar="{ record }">
          <a-avatar v-if="!record.avatarUrl" :auto-fix-font-size="true" :size="50">{{ record.name.substr(0, 1)
          }}</a-avatar>
          <a-avatar v-if="record.avatarUrl" :size="50" :imageUrl="record.avatarUrl"></a-avatar>
        </template>

        <template #sex="{ record }">
          {{ record.sex == "1" ? "男" : " 女" }}
        </template>

        <template #action="{ record }">
          <a-space>
            <a-button type="text" size="mini" @click="editRecord(record)">编辑</a-button>
            <a-popconfirm content="确认操作该学生留级吗？" @ok="showKeepGradeDialog(record)">
              <a-button type="text" size="mini">留级</a-button>
            </a-popconfirm>
            <a-popconfirm content="确认要删除该数据吗？" @ok="deleteRecord(record)">
              <a-button type="text" size="mini">删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-card>
    <a-modal v-model:visible="visible" width="800px" title="新增学生" :footer="null">
      <a-form ref="submitForm" size="large" :label-col-props="{ span: 8 }" :wrapper-col-props="{ span: 16 }"
        :model="submitData" @submit-success="handleSubmitSuccess">
        <a-row>
          <a-col :span="12">
            <a-form-item field="schoolId" label="选择学校">
              <a-select v-model="submitData.schoolId" placeholder="请选择学校" allow-clear @change="schoolSubmitChange">
                <a-option v-for="s in schoolList" :key="s.id" :label="s.name" :value="s.id"></a-option>
              </a-select>
            </a-form-item>
            <a-form-item field="name" label="姓名" :rules="[{ required: true, message: '请输入姓名' }]">
              <a-input v-model="submitData.name" placeholder="请输入姓名" />
            </a-form-item>
            <a-form-item field="sex" label="性别" :rules="[{ required: true, message: '请选择性别' }]">
              <a-radio-group v-model="submitData.sex">
                <a-radio value="1">男</a-radio>
                <a-radio value="2">女</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item field="studyCode" label="学籍号" :rules="[{ required: true, message: '请输入学籍号' }]">
              <a-input v-model="submitData.studyCode" placeholder="请输入学籍号" />
            </a-form-item>
            <a-form-item field="classesId" label="年级/班级" :rules="[{ required: true, message: '请选择所属年级/班级' }]">
              <a-space>
                <a-select v-model="submitData.gradeId" style="width: 100px" @change="changeSubmitGrade"
                  placeholder="年级">
                  <a-option v-for="item in submitGradeClassesList" :key="item.id" :value="item.id">{{ item.name
                  }}</a-option>
                </a-select>
                <a-select v-model="submitData.classesId" style="width: 100px" placeholder="班级">
                  <a-option v-for="classes in submitClassesList" :key="classes.id" :value="classes.id">{{ classes.name
                  }}</a-option>
                </a-select>
              </a-space>
            </a-form-item>
            <a-form-item field="nation" label="民族">
              <a-select v-model="submitData.nation" style="width: 100%" placeholder="请选择民族">
                <a-option v-for="item in constants.nationList" :key="item.value" :value="item.value">{{ item.label
                }}</a-option>
              </a-select>
            </a-form-item>
            <a-form-item field="birthday" label="出生日期">
              <a-date-picker v-model="submitData.birthday" style="width: 100%" placeholder="请选择出生日期" />
            </a-form-item>
            <a-form-item field="fromSource" label="学生来源">
              <a-input v-model="submitData.fromSource" placeholder="请输入学生来源" />
            </a-form-item>
            <a-form-item field="address" label="家庭地址">
              <a-input v-model="submitData.address" placeholder="请输入家庭地址" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="avatarUrl" label="头像">
              <UploadAvatar v-model:url="submitData.avatarUrl" :uploadData="uploadData"
                action="/admin/v1/student/photoUpload" />
            </a-form-item>
            <a-form-item field="idNumber" label="身份证号">
              <a-input v-model="submitData.idNumber" placeholder="请输入身份证号" />
            </a-form-item>
            <a-form-item field="cardNo" label="IC卡号">
              <a-input v-model="submitData.cardNo" placeholder="请输入IC卡号" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item>
          <a-space>
            <a-button html-type="submit" type="primary">保存</a-button>
            <a-button @click="() => {
              visible = false;
            }
            ">取消</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal v-model:visible="showUpdateGradeDialog" width="600px" :footer="null" :hide-cancel="true" :draggable="true"
      title="一键升班">
      <a-form :model="updateGradeModel">
        <a-form-item>
          <div style="color: #666;font-size: 14px;">注：一键升班操作后，大四学生将变为已毕业状态，大三将升级为大四，大二将升级为大三，大一将升级为大二</div>
        </a-form-item>
        <a-form-item label="指定学籍号">
          <div style="width: 100%;">
            <a-textarea style="height: 100px;width: 100%;" v-model="updateGradeModel.includeStudyCodeStr"
              placeholder="请输入需要升班操作的学籍号,按英文逗号分开，示例 201333,202311"></a-textarea>
            <div style="color: #666;font-size: 14px;">若不输入该字段，默认全校所有学生进行统一升班操作</div>
          </div>
        </a-form-item>
        <a-form-item label="排除学籍号">
          <div style="width: 100%;">
            <a-textarea style="height: 100px;" v-model="updateGradeModel.excludeStudyCodeStr"
              placeholder="请输入需要排除升班操作的学籍号,按英文逗号分开，示例 201333,202311"></a-textarea>
            <div style="color: #666;font-size: 14px;">若输入该字段，将不会对输入的学籍号进行升班操作</div>
          </div>
        </a-form-item>
        <!-- <a-form-item label="保留原有班级">
        <a-switch v-model="updateGradeModel.keepOldClasses"></a-switch>
        <div style="color: #666;font-size: 12px;padding-left: 15px;">升班后是否保留原有班级</div>
      </a-form-item> -->
        <a-form-item>
          <a-popconfirm content="确认执行一键升班操作吗？" @ok="updateGradeSuccess">
            <a-button type="primary">确认</a-button>
          </a-popconfirm>
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal v-model:visible="uploadVisible" width="600px" :hide-cancel="true" :draggable="true" @ok="closeUploadDialog"
      title="导入学生数据">
      <a-space direction="vertical" style="width: 100%; text-align: center">
        <div style="color: #999">
          <div>本平台为互联网非涉密平台，严禁处理、传输国家秘密、工作秘密及敏感信息。请确认扫描、传输的文件资料不涉及上述信息。</div>
          <div>暂时只支持符合导入模板要求的文件进行上传，请按需下载导入模板，编辑后再上传</div>
        </div>
        <a-button type="link" href="/学生导入.xlsx" style="margin-bottom: 10px">导入学生模板下载</a-button>
        <Upload :uploadData="uploadData" v-model:uploadErrorList="uploadErrorList" accept=".xls,.xlsx" :draggable="true"
          action="/admin/v1/student/import" />
        <div class="upload-error-con" v-if="uploadErrorList && uploadErrorList.length > 0">
          <div class="title">错误信息：</div>
          <div class="upload-error-item" v-for="error in uploadErrorList" :key="error">
            {{ error }}
          </div>
        </div>
      </a-space>
    </a-modal>
    <a-modal v-model:visible="avatarUploadVisible" width="600px" :hide-cancel="true" :draggable="true"
      @ok="closeUploadDialog" title="导入学生头像">
      <a-space direction="vertical" style="width: 100%; text-align: center">
        <div style="color: #999">暂时只支持.zip文件，压缩包内以学籍号作为头像图片的文件名</div>
        <Upload :draggable="true" accept=".zip" action="/admin/v1/student/photoImport" />
      </a-space>
    </a-modal>
    <a-modal v-model:visible="changeClassesVisible" width="600px" :hide-cancel="true" :draggable="true"
      :title="changeDialogTitle" :footer="null">
      <a-form :model="changeClassData" ref="changeClassForm" @submit-success="sureChangeClasses">
        <a-form-item field="classesId" label="选择转入班级" :rules="[{ required: true, message: '请选择转入班级' }]">
          <a-space>
            <a-select :disabled="isChangeClasses" v-model="changeClassData.gradeId" style="width: 100px"
              @change="changeClassesSubmitGrade" placeholder="年级">
              <a-option v-for="item in gradeClassesList" :key="item.id" :value="item.id">{{ item.name }}</a-option>
            </a-select>
            <a-select v-model="changeClassData.classesId" style="width: 150px" placeholder="班级">
              <a-option v-for="classes in changeClassesList" :key="classes.id" :value="classes.id">{{ classes.name
              }}</a-option>
            </a-select>
          </a-space>
        </a-form-item>
        <a-form-item>
          <a-space size="large" style="margin-top: 16px">
            <a-button html-type="submit" type="primary">确认</a-button>
            <a-button @click="changeClassesVisible = false">取消</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped></style>
